package com.by.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.config.RabbitMqUtils;
import com.by.entity.Order;
import com.by.entity.dto.OrderDto;
import com.by.entity.vo.ShopCartItemVo;
import com.by.mapper.OrderAddrMapper;
import com.by.mapper.OrderMapper;
import com.by.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private OrderAddrMapper orderAddrMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitMqUtils rabbitMqUtils;

    private final String HALF_CACHE_KEY = "cart";


    @Override
    @Transactional
    public Order createOrder(OrderDto orderDto) {
        String userId="1";
        String key=HALF_CACHE_KEY+userId;
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(key);
        Map<Object, Object> entries = boundHashOps.entries();
        List<ShopCartItemVo> ShopCartItemVoList = new ArrayList<>();
        entries.forEach((k, v) -> {
            ShopCartItemVoList.add(JSONUtil.toBean((String) v, ShopCartItemVo.class));
        });
        //TODO 购物车信息保存到数据库中
        Order order = new Order();
        //雪花算法，生成订单id getSnowflake（）里面的数字不同，生成的订单id不一样
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long orderId = snowflake.nextId();
        order.setOrderId(orderId);
        order.setUserId(Long.parseLong(userId));
        //order.setTotal(ShopCartItemVoList.stream().mapToDouble(ShopCartItemVo::getItemTotalPrice).sum());
        BeanUtil.copyProperties(orderDto, order);
        //直接返回order信息 mq异步保存订单基础信息到数据库中
        rabbitMqUtils.sendMessage(JSONUtil.toJsonStr(order));
        return order;
    }
}
